package com.summer.safe.utils;

import com.alibaba.fastjson.JSON;
import com.summer.safe.base.Principal;
import com.summer.safe.system.dao.*;
import com.summer.safe.system.entity.*;
import com.summer.safe.system.dao.*;
import com.summer.safe.system.entity.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.List;


/**
 * 用户管理
 * @author
 */
public class UserUtils {
	private static UserDao userDao = SpringContextUtil.getBean(UserDao.class);
	private static RoleDao roleDao = SpringContextUtil.getBean(RoleDao.class);
	private static MenuDao menuDao = SpringContextUtil.getBean(MenuDao.class);
	private static AreaDao areaDao = SpringContextUtil.getBean(AreaDao.class);
	private static OfficeDao officeDao = SpringContextUtil.getBean(OfficeDao.class);



	/**
	 * app根据用户ID获取用户信息
	 * @param
	 * @return User
	 */
	public static final String userId = "userId";






	/**
	 * 根据登录名获取用户
	 * @param loginName
	 * @return 取不到返回null
	 */
	public static User getByLoginName(String loginName){
		User user = (User) CacheUtils.get(Global.USER_CACHE, Global.USER_CACHE_LOGIN_NAME_ + loginName);
		if (user == null){
			/*user = userDao.getByLoginName(new User(null, loginName));*/
			user = userDao.getByLoginName(loginName);
			if (user == null){
				return null;
			}
			user.setRoleList(roleDao.findList(new Role(user)));
			CacheUtils.put(Global.USER_CACHE, Global.USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(Global.USER_CACHE, Global.USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
		return user;
	}

	/**
	 * 获取当前用户
	 * @return 返回 JSONObject
	 */
	public static String getUserJson(){
		return JSON.toJSONString(getUser());
	}




	/**
	 * 获取当前用户角色列表
	 * @return
	 */
	public static List<Role> getRoleList(){
		@SuppressWarnings("unchecked")
		List<Role> roleList = (List<Role>)getCache(Global.CACHE_ROLE_LIST);
		if (roleList == null){
			User user = getUser();
			if (user.isAdmin()){
				roleList = roleDao.findAllList(new Role());
			}else{
				Role role = new Role();
				//role.getSqlMap().put("dsf", BaseService.dataScopeFilter(user.getCurrentUser(), "o", "u"));
				roleList = roleDao.findList(role);
			}
			putCache(Global.CACHE_ROLE_LIST, roleList);
		}
		return roleList;
	}

	/**
	 * 获取当前用户授权菜单
	 * @return
	 */
	public static List<Menu> getMenuList(){
		@SuppressWarnings("unchecked")
		List<Menu> menuList = (List<Menu>)getCache(Global.CACHE_MENU_LIST);
		if (menuList == null){
			User user = getUser();
			if (user.isAdmin()){
				menuList = menuDao.findAllList(new Menu());
			}else{
				Menu m = new Menu();
				m.setUserId(user.getId());
				menuList = menuDao.findByUserId(m);
			}
			putCache(Global.CACHE_MENU_LIST, menuList);
		}
		return menuList;
	}



	/**
	 * 获取所有区域
	 * @return
	 */
	public static List<Area> getAreaAllList(){
		@SuppressWarnings("unchecked")
		List<Area> areaList = (List<Area>)getCache(Global.CACHE_AREA_ALL_LIST);
		if (areaList == null){
			areaList = areaDao.findAllList(new Area());
			putCache(Global.CACHE_AREA_ALL_LIST, areaList);
		}
		return areaList;
	}

	/**
	 * 获取当前用户有权限访问的区域
	 * @return
	 */
	public static List<Area> getAreaList(){
		List<Area> areaList = (List<Area>)getCache(Global.CACHE_AREA_LIST);
		if (areaList == null){
			User user = getUser();
			if (user.isAdmin()){
				areaList = areaDao.findAllList(new Area());
			}else{
				Area area = user.getOffice().getArea();
				areaList = areaDao.findList(area);
			}
			putCache(Global.CACHE_AREA_LIST, areaList);
		}
		return areaList;
	}


	/**
	 * 获取当前用户有权限访问的部门
	 * @return
	 */

	public static List<Office> getOfficeList(){
		User user=getUser();
		@SuppressWarnings("unchecked")
		List<Office> officeList = (List<Office>)getCache(Global.CACHE_OFFICE_LIST);
		if (officeList == null){
			if (user.isAdmin()){
				officeList = officeDao.findAllList(new Office());
			}else {
				Office office = new Office();
				//office.getSqlMap().put("dsf", DataScope.dataScopeFilter("a"));
				/*office.setSqlMap((Map<String, String>) CacheUtils.get(user.getId()));

				officeList = officeDao.findList(office);*/
				office.setUserId(user.getId());
				officeList = officeDao.getRoleOffice(office);
				CacheUtils.remove(user.getId());
			}
			putCache(Global.CACHE_OFFICE_LIST, officeList);
			}
			return officeList;
	}


	/**
	 * 获取当前用户授权的部门
	 * @return
	 */
	/*public static List<Office> getNewOfficeList(){
		@SuppressWarnings("unchecked")
		List<Office> officeList = (List<Office>)getCache(Global.CACHE_OFFICE_LISTa);
		if (officeList == null){
			User user = getUser();
			if (user.isAdmin()){
				officeList = officeDao.findAllList(new Office());
			}else{
				Office office = new Office();
				office.setUserId(user.getId());
				officeList = officeDao.getRoleOffice(office);
			}
			putCache(Global.CACHE_OFFICE_LISTa, officeList);
		}
		return officeList;
	}*/

	/**
	 * 获取所有部门信息
	 * @return
	 */
	public static List<Office> getOfficeAllList(){
		@SuppressWarnings("unchecked")
		List<Office> officeList = officeDao.findAllList(new Office());
		return officeList;
	}
	/**
	 * 获取当前用户
	 * @return 取不到返回 new User()
	 */
	public static User getUser(){
		Subject subject = SecurityUtils.getSubject();
		Principal principal = (Principal)subject.getPrincipal();
		if (principal!=null){
			User user = get(principal.getId());
			if (user != null){
				return user;
			}
			return new User();
		}
		// 如果没有登录，考虑是否APP接口访问,则返回实例化空的User对象。
		return  null;
	}

	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public static User get(String id){
		User user = (User) CacheUtils.get(Global.USER_CACHE, Global.USER_CACHE_ID_ + id);
		if (user ==  null){
			user = userDao.get(id);
			if (user == null){
				return null;
			}
			user.setRoleList(roleDao.findList(new Role(user)));
			CacheUtils.put(Global.USER_CACHE, Global.USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(Global.USER_CACHE, Global.USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
		return user;
	}



	public static Session getSession(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null){
				session = subject.getSession();
			}
			if (session != null){
				return session;
			}
//			subject.logout();
		}catch (InvalidSessionException e){

		}
		return null;
	}

	/**
	 * 清除系统缓存
	 */
	public static void clearCache(){
		//角色缓存
		removeCache(Global.CACHE_ROLE_LIST);
		//按钮缓存
		removeCache(Global.CACHE_MENU_LIST);
		//当前用户有权限访问的区域缓存
		removeCache(Global.CACHE_AREA_LIST);
		//所有区域缓存
		removeCache(Global.CACHE_AREA_ALL_LIST);

		//获当前用户有权限访问的部门缓存
		removeCache(Global.CACHE_OFFICE_LIST);
		//所有部门信息缓存
		removeCache(Global.CACHE_OFFICE_ALL_LIST);
		/*清除当前用户Cache中的数据*/
		UserUtils.clearCache(getUser());

		//移除演示环境
		SessionUtils.removeSessionAttribute("demomode");
		//移除配置环境
		SessionUtils.removeSessionAttribute("profiles");
	}

	/**
	 * 清除指定用户缓存
	 * @param user
	 */
	public static void clearCache(User user){
		CacheUtils.remove(Global.USER_CACHE, Global.USER_CACHE_ID_ + user.getId());
		CacheUtils.remove(Global.USER_CACHE, Global.USER_CACHE_LOGIN_NAME_ + user.getLoginName());
		CacheUtils.remove(Global.USER_CACHE, Global.USER_CACHE_LOGIN_NAME_ + user.getOldLoginName());
		if (user.getOffice() != null && user.getOffice().getId() != null){
			CacheUtils.remove(Global.USER_CACHE, Global.USER_CACHE_LIST_BY_OFFICE_ID_ + user.getOffice().getId());
		}
	}
	// ============== User Cache ==============

	public static Object getCache(String key) {
		return getCache(key, null);
	}

	public static Object getCache(String key, Object defaultValue) {
		Object obj = getSession().getAttribute(key);

		return obj==null?defaultValue:obj;
	}

	public static void putCache(String key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static void removeCache(String key) {
		getSession().removeAttribute(key);
	}
}
